<template>
  <div class="container  order-list">
    <!-- 面包屑导航 -->
    <breadcrumb :breadcrumbConfig = breadcrumbConfig></breadcrumb>
    <!-- 面包屑导航 -->

    <div class="content page-title">
      <h2>提交订单</h2>
    </div>

    <div class="step">
      <!-- stepsData.active -->
      <el-steps :active="2" align-center>
        <el-step :title="item" v-for="item in stepsData.list"></el-step>
      </el-steps>
    </div>
    <div class="content">
      <h3>数据筛选</h3>
       <el-row :gutter="20">
            <el-col :span="5"
              ><span class="details_title">客户姓名</span
              ><span class="details_value">张三</span></el-col
            >
            <el-col :span="5"
              ><span class="details_title">手机号码1</span
              ><span class="details_value">15862526362</span></el-col
            >
            <el-col :span="5"
              ><span class="details_title"> 手机号码2</span
              ><span class="details_value">-</span></el-col
            >
            <el-col :span="4"
              ><span class="details_title">性别</span
              ><span class="details_value">男</span></el-col
            >
            <el-col :span="5"
              ><span class="details_title">年龄</span
              ><span class="details_value">17</span></el-col
            >

        </el-row>
        <el-row :gutter="20" style="border-top:0">
            <el-col :span="5"
              ><span class="details_title">购买次数</span
              ><span class="details_value">15615161570128</span></el-col
            >
            <el-col :span="5">
              <span class="details_title">客户意向</span>
                <el-select size="mini" v-model="optionsValue" placeholder="请选择" style="width:120px;padding-left:30px">
                  <el-option
                    v-for="item in optionslabel"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-col>
            <el-col :span="5"
              ><span class="details_title">客户等级</span
              ><span class="details_value">A级</span></el-col
            >
            <el-col :span="4"
              ><span class="details_title">入线方式</span
              ><span class="details_value">B125262</span></el-col
            >
            <el-col :span="5"
              ><span class="details_title">创建时间</span
              ><span class="details_value">2022-10-21</span></el-col
            >

        </el-row>
    </div>
    <div class="content">
      <div class="headerTitle shopTitle">选择收货地址</div>
        <lb-table :column="column" :data="dataList.list"></lb-table>
    </div>
    <div class="orderBox">
      <div class="order">
        <p class="headerTitle shopTitle" >已选商品</p>
          <lb-table
        :column="columnShop"
        :data="tableData"
      >
      </lb-table>
      </div>
       <div class="orderNotes" >
          <div class="headerOrder">
            <div  class="orderRemak ">订单备注</div>
          </div>
          <div class="notes">
            <el-input
                maxlength="200"
                type="textarea"
                 show-word-limit
                v-model="textarea"
                placeholder="备注"
            ></el-input>

          </div>
        </div>
        <div class="statistics">
          <p class="fourteen">
            <span>总计：共 {{ orderNumber }} 件 </span>
          </p>
          <p class="fourteen">
            <span>商品总价：￥{{giftPrice }}</span>
          </p>
           <p class="fourteen">
            <span>运费￥{{giftPrice }}</span>
          </p>
          <p style="margin-right:20px">
            <span >应付:￥200</span>
          </p>
          <p style="margin-right:20px">
            <span class="blue">(已收:￥200)</span>
          </p>
        </div>
        <div class="auditRadio">
          <span>是否审核:</span>
          <div >
            <el-radio-group v-model="form.resource">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </div>
        </div>

    </div>
     <div class="present"><el-button class="closeorder" style="border: 1px solid #4168E7;"> 取消订单</el-button><el-button class="generateOrder" type="primary" @click="toReviewOrder">生成订单</el-button>
          </div>
    </div>

</template>

<script>
import formFiled from '@/components/form/index'
import breadcrumb from '@/components/breadcrumb'
import LbTable from '../../components/lb-table/lb-table'

export default {
  components: {
    formFiled,
    breadcrumb,
    LbTable
  },
  data () {
    return {
      form: {
        resource: ''
      },
      stepsData: {
        active: 0,
        list: ['选购商品', '提交订单', '支付订单', '提交审核']
      },
      breadcrumbConfig: {
        list: [
          {
            title: '订单拉取',
            type: '#ff0000',
            path: '/'
          },
          {
            title: '提交订单',
            type: '1',
            path: '/'
          }

        ]
      },
      optionslabel: [
        {
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }
      ],
      optionsValue: '',
      searchFormConfig: {
        formconfig: {
          labeWidth: 70, // 表单宽度
          itemList: [// 表单的list
            { type: 'input', prop: 'inputa', placeholder: '请输入内容', label: '商品名称', size: 'small' },
            { type: 'input', prop: 'inputb', placeholder: '请输入内容', label: '商品编号', size: 'small' },
            { type: 'select', prop: 'selectPropa', placeholder: '请选择内容', label: '商品类目', size: 'small', option: [{ label: '选择一', value: 'key1' }, { label: '选择二', value: 'key2' }] },
            {
              type: 'select', prop: 'selectPropb', placeholder: '请选择内容', label: '品牌', size: 'small',
              option: [{ label: '选择一', value: 'key1' }, { label: '选择二', value: 'key2' }]
            },
            {
              type: 'select', prop: 'selectPropc', placeholder: '请选择内容', label: '商品类型', size: 'small',
              option: [{ label: '选择一', value: 'key1' }, { label: '选择二', value: 'key2' }]
            }
          ],
          btnarry: [// 表单按钮
            { name: '查询', click: 'add', type: 'primary', plain: true, size: 'small' },
            { name: '重置', click: 'clrear', type: 'primary', plain: true, size: 'small' }
          ]
        },
        formData: { // 表单提交数据，
          checkbox: []// 注：如果类型是checkbox，必须foemData里边提前声明数组
        }
      },
      goods: {
        name: '',
        brand: '',
        category: [],
        code: ''
      },
      activeName: 'goods',
      total: 0,
      giftPrice: 0,
      receivedMoney: '',
      tableData: [],
      currentPage1: 1,
      pageSizegoods: 10,
      // pageZp: 1,
      currentPageZp: 1,
      pageSizeZp: 10,
      id: '',
      brandselect: [],
      options: [],
      addressId: '',
      goodsL: [],
      giftL: [],
      orderNumber: 0,
      origTotal: 0, // 原价
      arry: [],
      arrayZp: [],
      taskId: '',
      isChange: '', // 判断是否是修改的订单
      customerId: '',
      orderId: '',
      textarea: '',
      pingZ: false,
      imageUrl: '',
      Img: '',
      fileList: [],
      voucher: '',
      channelOrderId: '', // 分配条件开单

      dataList: [],
      page: {
        pageNo: 1,
        pageSize: 10,
        totalNum: 0,
        currentPage: 1
      },
      column: [{
        label: '收货人',
        prop: 'index'
      }, {
        label: '手机号码',
        prop: 'code'
      },
      {
        label: '地区',
        prop: 'updatedTime'
      },
      {
        label: '详细地址',
        prop: 'title'
      },
      {
        label: '默认地址',
        prop: 'barndId'
      },
      {
        label: '操作',
        render: (h, scope) => {
          return (
            <div style='text-align: center;'>
              <p style='margin-top:10px'> <el-button size='mini' type='primary' onClick={() => { this.addOrder(scope.row, scope.$index) }}>更改</el-button></p>
            </div>

          )
        }
      }],
      columnGift: [{
        label: '序号',
        prop: 'index'
      }, {
        label: '赠品编号',
        prop: 'code'
      },
      {
        label: '赠品图片',
        prop: 'updatedTime'
      },
      {
        label: '赠品名称',
        prop: 'title'
      },
      {
        label: '赠品品牌',
        prop: 'barndId'
      },
      {
        label: '赠品类目',
        prop: 'categoryId'
      },
      {
        label: '赠品类型',
        prop: 'typeId'
      },
      {
        label: '价格',
        prop: 'title'
      },
      {
        label: '赠品规格',
        prop: 'specificationName'
      },
      {
        label: '可用库存',
        prop: 'quantityStock'
      },
      {
        label: '操作',
        render: (h, scope) => {
          return (
            <div>
              <el-link
                size='mini'
                type='primary'
                onClick={() => { this.addOrder(scope.row, scope.$index) }}>添加商品</el-link>
            </div>
          )
        }
      }],
      columnShop: [{
        label: '商品信息',
        prop: 'updatedTime'
      },
      {
        label: '单价/数量',
        render: (h, scope) => {
          return (
            <div>
              <el-link
                size='mini'
                type='primary'
                onClick={() => { this.addOrder(scope.row, scope.$index) }}>添加商品</el-link>
            </div>
          )
        }
      },
      {
        label: '小计',
        render: (h, scope) => {
          return (
            <p>{ parseFloat(scope.row.total).toFixed(2) }</p>
          )
        }
      }
      ]
    }
  },
  created () {
    // this.id=this.$route.query.id;
    this.taskId = this.$route.query.taskId
    this.isChange = this.$route.query.isChange // 1为改单
    this.orderId = this.$route.query.orderId
    this.customerId = this.$route.query.userId
    this.addressId = this.$route.query.addressId
    this.pingZ = this.$route.query.pingZ
    if (this.$route.query.channelOrderId) {
      this.channelOrderId = this.$route.query.channelOrderId
    }

    if (!this.is_null(this.pingZ)) {
      this.pingZ = true
    }
    this.voucher = JSON.parse(sessionStorage.getItem('voucher'))
    if (!this.is_null(this.voucher)) {
      this.textarea = this.voucher.note
      this.fileList = this.voucher.fileImg
    }

    if (this.$route.query.orderCommodityList) {
      // 判断是否是路由传参
      this.tableData = this.$route.query.orderCommodityList
      for (const item of this.tableData) {
        item.title = item.name
        item.sellPrice = item.price
      }
      this.tableZp = this.$route.query.orderComplimentaryList
    } else {
      this.tableData = JSON.parse(sessionStorage.getItem('goodsList'))
      this.tableZp = JSON.parse(sessionStorage.getItem('giftList'))
    }

    if (!this.is_null(this.tableData)) {
      // this.tableData不为空，就执行计算
      for (let i = 0; i < this.tableData.length; i++) {
        this.arry.push(this.tableData[i].id)
      }
      for (let i = 0; i < this.tableZp.length; i++) {
        this.arrayZp.push(this.tableZp[i].id)
      }
      this.calculation()
      this.receivedMoney = this.$route.query.receivedMoney
      this.total = this.$route.query.total
    } else {
      // if (!this.$route.query) {
      this.tableData = []
      this.tableZp = []
      // }
    }
    this.brandSelectBox()
    this.brandSelect()
    // this.getDefaultAddress();
    document.onkeydown = (e) => {
      const key = window.event.keyCode
      if (key == 13) {
        this.searchGoods()
      }
    }
  },
  methods: {
    // 接受表单组件的数据
    dialogClick (val) {
      // this.formFiledData = Object.assign(this.formFiledData, val)
      // console.log(this.formFiledData,'接受表单组件的数据');
    },
    is_null (content) {
      if (content) {
        return false
      } else {
        return true
      }
    },
    reset () {
      this.goods = {
        name: '',
        brand: '',
        category: [],
        code: ''
      }
      this.currentPageZp = 1
      this.pageSizeZp = 10
      this.currentPage1 = 1
      this.pageSizegoods = 10

      this.giftList()
    },
    searchGoods () {
      this.currentPage1 = 1
      this.pageSizegoods = 10
    },
    searhgift () {
      this.currentPageZp = 1
      this.pageSizeZp = 10
      this.giftList()
    },

    handleCurrentChange (val) {
      this.currentPage1 = val
    },
    handleSizeChange (val) {
      this.pageSizegoods = val
    },
    // 添加商品、赠品
    addOrder (row) {
      // console.log(row)
      const rows = {
        // 初始化默认状态
        createdTime: row.createdTime,
        id: row.id,
        number: 1,
        sellPrice: row.sellPrice,
        specificationName: row.specificationName,
        title: row.title,
        total: 1 * parseInt(row.sellPrice),
        brandId: row.brandId,
        typeId: row.typeId
      }
      let numb = 0
      let price = 0
      // 判断商品是否重复
      if (this.tableData.length != 0) {
        if (this.arry.indexOf(row.id) >= 0) {
          let setNum = 0
          let indexTab = 0
          // 获取需要改变数量得值
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].id == row.id) {
              setNum = parseInt(this.tableData[i].number) + 1
              indexTab = i
            }
          }
          // 获取需要改变数量得值
          this.$set(this.tableData, indexTab, {
            createdTime: row.createdTime,
            id: row.id,
            number: setNum,
            sellPrice: row.sellPrice,
            specificationName: row.specificationName,
            title: row.title,
            total: setNum * parseInt(row.sellPrice),
            brandId: row.brandId,
            typeId: row.typeId
          })
        } else {
          this.arry = []
          this.tableData.push(rows)
          // 不相同则需要插入id
          for (let i = 0; i < this.tableData.length; i++) {
            this.arry.push(this.tableData[i].id)
          }
          // 不相同则需要插入id
        }
      } else {
        // tableData为空的时候
        this.arry = [] // 初始化一次再push
        this.tableData.push(rows)
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].total =
                  this.tableData[i].number * this.tableData[i].sellPrice
          this.arry.push(this.tableData[i].id) // 需要集合商品id
        }
      }
      // 判断商品是否重复
      // 赠品数量
      let zpNum = 0
      let zpPrice = 0
      for (let i = 0; i < this.tableZp.length; i++) {
        zpNum += Number(this.tableZp[i].number)
        zpPrice += Number(this.tableZp[i].total)
      }
      for (let i = 0; i < this.tableData.length; i++) {
        numb += Number(this.tableData[i].number)
        price += Number(this.tableData[i].total)
      }
      this.orderNumber = Number(numb) + Number(zpNum)
      this.origTotal = price + zpPrice
      this.total = this.origTotal
      this.giftPrice = zpPrice.toFixed(2)
    },

    //* * 品牌下拉 **//
    brandSelectBox () {
      this.axios
        .get('/order/comm/commodity/selectList', {
          headers: {
            isLoading: false
          }
        })
        .then((res) => {
          // console.log('分类')
          // console.log(res);
          if (res.code == 0) {
            this.brandselect = res.data
          } else {
            this.$message.error(res.message)
          }
        })
    },
    //* * 品牌下拉 **//
    // 分类下拉框
    brandSelect () {
      this.axios
        .get('/order/comm/commodity/selectBrand', {
          headers: {
            isLoading: false
          }
        })
        .then((res) => {
          if (res.code == 0) {
            this.options = res.data
          } else {
            this.$message.error(res.message)
          }
        })
    },
    // handleChangeZp(val) {
    // 	this.giftList(`${val}`);
    // },

    handleChangeZp (val) {
      this.currentPageZp = val
      this.giftList()
    },
    handleSizeChangeZp (val) {
      this.pageSizeZp = val
      this.giftList()
    },
    // 加减号
    changeQuantity (row, type, index) {
      if (type > 0) {
        row.number++
      } else {
        row.number--
        row.number > 1 ? row.number : (row.number = 1)
      }
      // this.changeCount(row,type,index);
      this.calculation()
      this.$set(this.tableData, index, {
        createdTime: row.createdTime,
        id: row.id,
        number: row.number,
        sellPrice: row.sellPrice,
        specificationName: row.specificationName,
        title: row.title,
        total: parseFloat(row.number * row.sellPrice).toFixed(2),
        brandId: row.brandId,
        typeId: row.typeId
      })
      this.tableData[index].number = row.number
      // console.log(this.tableData[index].number+"修改后的数量")
    },
    // 数量文本框值改变
    changeCount (row, index) {
      if (
        row.number == null ||
              row.number == '' ||
              (row.number != 'number' && isNaN(row.number))
      ) {
        row.number = 1
      } else if (row.number <= 1) {
        row.number = 1
        this.$message({
          message: '已经减到最低了哦',
          type: 'warning'
        })
      }
      this.$set(this.tableData, index, {
        createdTime: row.createdTime,
        id: row.id,
        number: row.number,
        sellPrice: row.sellPrice,
        specificationName: row.specificationName,
        title: row.title,
        total: parseFloat(row.number * row.sellPrice).toFixed(2),
        brandId: row.brandId,
        typeId: row.typeId
      })
      this.tableData[index].number = row.number
      this.calculation()
    },

    /** 修改商品的单价**/
    changePrice (row, index) {
      if (!this.is_null(row.sellPrice)) {
        this.$set(this.tableData, index, {
          createdTime: row.createdTime,
          id: row.id,
          number: row.number,
          sellPrice: row.sellPrice,
          specificationName: row.specificationName,
          title: row.title,
          total: parseFloat(Number(row.number) * Number(row.sellPrice)).toFixed(
            2
          ),
          brandId: row.brandId,
          typeId: row.typeId
        })
      } else {
        this.$message.warning('单价不能为空')
      }
      this.calculation()
    },
    /** 修改商品的单价**/

    /** 修改赠品的单价**/

    // 计算价格--公共调用 总价，总数量
    calculation () {
      let zpNum = 0
      let numb = 0 // 接收商品数量
      let zpPrice = 0
      let price = 0
      for (let i = 0; i < this.tableZp.length; i++) {
        zpNum += Number(this.tableZp[i].number)
        zpPrice += Number(this.tableZp[i].number) * this.tableZp[i].sellPrice
      }
      for (let i = 0; i < this.tableData.length; i++) {
        numb += Number(this.tableData[i].number)
        price += Number(this.tableData[i].number) * this.tableData[i].sellPrice
      }
      this.orderNumber = Number(numb) + Number(zpNum)
      this.origTotal = parseFloat(price + zpPrice).toFixed(2)
      this.total = parseFloat(this.origTotal).toFixed(2)
      this.giftPrice = zpPrice.toFixed(2)
      // this.receivedMoney = this.total;
    },
    // 删除
    delectRow (index) {
      this.tableData.splice(index, 1)
      this.arry.splice(index, 1)
      // console.log(this.arry+"--this.arry--// 删除")
      this.calculation()
    },

    // 上传凭证
    proofImport (fileObj) {
      const formData = new FormData()
      formData.append('file', fileObj.file)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios
        .post(
          '/sys/v1/common/upload/files?pathName=internalSystem',
          formData,
          config,
          {
            header: {
              isLoading: false
            }
          }
        )
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.Img = res.data.url
            const obj = {
              img: this.Img
            }
            this.imageUrl.push(this.Img)
            this.fileList.push(obj)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch()
    },
    // 删除图片
    close (index) {
      this.fileList.splice(index, 1)
    },
    notesEvent () {
      const notes = {
        note: this.textarea,
        fileImg: this.fileList
      }
      sessionStorage.setItem('voucher', JSON.stringify(notes))
    },
    toReviewOrder () {
      if (this.tableData.length + this.tableZp.length <= 0) {
        this.$message.warning('未选择下单商品')
      } else if (
        this.is_null(this.customerId) &&
              !this.$route.query.orderId &&
              !this.$route.query.id
      ) {
        this.$message.warning('请返回客户列表重新下单')
      } else {
        // 保存信息至本地
        sessionStorage.setItem('goodsList', JSON.stringify(this.tableData))
        sessionStorage.setItem('giftList', JSON.stringify(this.tableZp))
        if (!this.is_null(this.pingZ)) {
          this.notesEvent()
        }
        if (!this.is_null(this.receivedMoney)) {
          if (
            Number(this.receivedMoney) <= Number(this.total) &&
                  Number(this.receivedMoney) >= 0
          ) {
            if (this.is_null(this.isChange)) {
              this.$router.push({
                name: 'reviewOrder',
                query: {
                  total: this.total,
                  giftPrice: this.giftPrice,
                  taskId: this.taskId,
                  customerId: !this.$route.query.orderId
                    ? this.customerId
                      ? this.customerId
                      : this.$route.query.id
                    : this.$route.query.userId,
                  addressId: this.addressId,
                  pingZ: this.pingZ,
                  receivedMoney: this.receivedMoney,
                  exchange: this.$route.query.exchange,
                  orderId: this.$route.query.orderId,
                  channelOrderId: this.channelOrderId
                }
              })
            } else if (this.isChange == 1) {
              this.$router.push({
                name: this.$route.query.isCommit == 2 ? 'wyUpdate' : 'fixOrder',
                query: {
                  total: this.total,
                  giftPrice: this.giftPrice,
                  taskId: this.taskId,
                  customerId: this.customerId,
                  addressId: this.addressId,
                  orderId: this.orderId,
                  receivedMoney: this.receivedMoney,
                  jage: this.$route.query.jage,
                  userIntention: this.$route.query.userIntention,
                  channelOrderId: this.channelOrderId
                }
              })
            }
          } else {
            this.$message.warning('已收金额不能大于总金额')
          }
        } else {
          this.$message.warning('已收款金额不能为空')
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .details_title{
      font-size: 15px;
      font-weight: 400;
      line-height: 0px;
      color: #999999;
      padding-left: 40px;
    }
    .details_value{
      font-size: 15px;
      font-weight: 400;
      line-height: 0px;
      color: #666666;
      padding-left:40px;
    }
    .el-row{
      border:1px solid #efefef;
      box-sizing: border-box;
      margin-left: 0px !important;
      margin-right: 0px !important;
      .el-col {
        line-height:39px;
      }
    }
.shopTitle{
  margin-bottom: 20px;
}
.closeorder{
  width: 120px;
  height: 36px;
  color: #4168E7;
  line-height: 0;
}
/deep/.el-textarea__inner{
  height: 132px;
}
.generateOrder{
   width: 120px;
  height: 36px;
  line-height: 0;
  margin-left: 17px;
}
/deep/ .el-button{border: none;}
.search-form{
  display: flex;
  flex-wrap: wrap;
  /deep/ .el-form-item{
    width: 100%;
    max-width: 350px;
    min-width: 300px;
    .el-form-item__content{
      .el-select{
        width: 100%;
      }
    }
  }
}
.orderNotes{
  margin-top: 24px;
  padding-bottom: 25px;
  border-bottom: 1px solid #D9D9D9;
  .headerOrder{
    .orderRemak{
    margin-bottom: 12px;
    font-size: 18px;
  }
  }

}
.statistics{
  margin-top:30px;
  display: flex;
  justify-content: right;
  align-items: center;
  .fourteen{
    font-size: 14px;
    padding-right: 20px;
  }
  .blue{
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 0px;
    color: #4168E7;
  }
}

.auditRadio{
  display:flex;
  justify-content: right;
  align-items: center;
  margin-top: 15px;
  span{
    margin-right: 20px;
  }
}
.present {
  display: flex;
  justify-content: right;
  height: 36px;
  margin-top: 30px ;
  padding-bottom: 28px;
}
</style>
